#include<iostream>
#include<unistd.h>
#include<fcntl.h>
#include<cstring>
#include<cerrno>

using namespace std;

//设置使用非阻塞的方式去IO
void SetNoBlock(int fd)
{
    int fl = fcntl(fd, F_GETFL);
    if(fl < 0)
    {
        cerr << "fcntl" << endl;
        return;
    }

    fcntl(fd, F_SETFL, fl | O_NONBLOCK);
    cout << "set fd" << "noblock" << endl;
}

int main()
{
    char buffer[1024];

    //将标准输入设置成为非阻塞的方式去读取
    SetNoBlock(0);

    while(true)
    {
        //默认IO是以阻塞的方式去读取的
        ssize_t n = read(0, buffer, sizeof(buffer) - 1);
        if(n > 0)
        {
            buffer[n] = 0;
            cout << buffer << endl;
        }
        else if(n == 0)
        {
            cout << "read done" << endl;
        }
        else
        {
            // 我们可以通过错误码来判断是读取出错还是缓冲区没有数据提供应用层读取
            //如果返回的错误码是EWOULDBLOCK, 则表示是读取缓冲区没有数据，否则就是读取异常
            if(errno == EWOULDBLOCK)
            {
                cout << "0 fd data not ready, try again!" << endl;
                //do otherthings
                sleep(1);
            }
            else
            {
                cerr << "read exception" << ", cerr: " << errno << ", errstring: " << strerror(errno) <<  endl;
            }
        }
    }

    return 0;
}